<template>
  <div class="app">
    <!-- 头部面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>基础数据</el-breadcrumb-item>
      <el-breadcrumb-item>学员管理</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 内容主体 -->
    <el-card class="box-card">
      <!-- 搜索框 -->
      <div slot="header" class="clearfix">
        <template>
          <selector  @func="tbadata"></selector>
        </template>
        <!-- 增加 -->
        <el-button style="padding: 3px 5px 3px 15px" type="text" @click="centerDiae">
          <i class="el-icon-circle-plus-outline" style="padding-right:5px;"></i>
          <b>新增学生</b>
        </el-button>
      </div>
      <!-- 班级信息列表 -->
      <el-table :data="tableData" style="width: 100%" :fit="true">
        <el-table-column type="index"></el-table-column>
        <el-table-column label="班级名称">
          <template slot-scope="scope">
            <span>{{ scope.row.className }}</span>
          </template>
        </el-table-column>
        <el-table-column label="学员姓名">
          <template slot-scope="scope">
            <span>{{ scope.row.stuName }}</span>
          </template>
        </el-table-column>
        <el-table-column label="性别">
          <template slot-scope="scope">
            <span>{{ scope.row.stuSex }}</span>
          </template>
        </el-table-column>
        <el-table-column label="手机号码">
          <template slot-scope="scope">
            <span>{{ scope.row.stuMobile }}</span>
          </template>
        </el-table-column>
        <el-table-column label="出生日期">
          <template slot-scope="scope">
            <span>{{ scope.row.stuBirthDay | formatDate}}</span>
          </template>
        </el-table-column>
        <el-table-column label="年龄">
          <template slot-scope="scope">
            <span>{{ scope.row.stuAge }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150">
          <template slot-scope="scope" v-show="tabwhether">
            <el-button size="mini" @click="handleEdit(scope,scope.$index)">编辑</el-button>
            <el-button size="mini" v-has type="danger" @click="handleDelete(scope)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <el-dialog
      :title="tabbao?'修改学员信息':'新增学员信息'"
      :visible.sync="centerDialogVisible"
      width="35%"
      center
      :append-to-body="true"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="100px"
        class="demo-ruleForm"
      >
        <el-form-item label="班级" prop="classId">
          <selector  :valaue.sync="ruleForm.classId"></selector>
        </el-form-item>
        <el-form-item label="学生名称" prop="stuName">
          <el-input v-model="ruleForm.stuName"></el-input>
        </el-form-item>
        <el-form-item label="生日" :required="true">
          <el-form-item prop="stuBirthDay">
            <el-date-picker
              type="date"
              format="yyyy 年 MM 月 dd 日"
              value-format="yyyy-MM-dd"
              v-model="ruleForm.stuBirthDay"
            ></el-date-picker>
          </el-form-item>
        </el-form-item>
        <el-form-item label="手机号" prop="stuMobile">
          <el-input v-model="ruleForm.stuMobile"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="stuSex">
          <el-radio-group v-model="ruleForm.stuSex">
            <el-radio label="男"></el-radio>
            <el-radio label="女"></el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="密码" prop="stuPassword">
          <el-input v-model="ruleForm.stuPassword"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button @click="resetForm('ruleForm')">取消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm')">{{tabbao?"修改":"添加"}}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>


<script>
import { formatDate } from "../../uilt/timeHandle.js"; //时间组件
import selector from "@/components/selector/selector"; //班级组件
import {mapActions} from 'vuex'
export default {
  components: {
    selector
   
  },
   inject:['reload'],
  data() {
    //手机号检测
    var checkAge = (rule, valueo, callback) => {
      let telstr = /^[1]([3-9])[0-9]{9}$/;
      if (!valueo) {
        return callback(new Error("手机号不能为空"));
      }
      setTimeout(() => {
        if (!telstr.test(valueo)) {
          callback(new Error("无效手机号"));
        } else {
          callback();
        }
      }, 1000);
    };
    var checkBge=(rule,valueo,callback)=>{
      let telstr= /^[\u4E00-\u9FA5]{2,4}$/;
      if(!valueo){
         return callback(new Error("名字不能为空"));
      }else if(!telstr.test(valueo)){
          callback(new Error("长度在 2 到 4 个汉字"));
      }else{
          callback();
      }
    }
    return {
      centerDialogVisible: false, //确认状态
      tabbao: false,
      tabwhether: false, //条件渲染
      tableData: [], //班级信息列表
      ruleForm: {
        //表单信息
        stuName: "", //名字
        classId: "", //班级选择
        stuBirthDay: "", //时间
        stuMobile: "", //手机号
        stuSex: "", //性别
        stuPassword: "", //密码
        stuUid: "",
        index: ""
      },
      rules: {
        //表单验证
        stuName: [
          //名字验证
          { required: true,validator: checkBge, trigger: "blur" }
        ],
        classId: [
          //班级选择
          { required: true, message: "请选择班级", trigger: "blur" }
        ],
        stuBirthDay: [
          //时间
          {
            message: "请选择日期",
            trigger: "change"
          }
        ],
        stuMobile: [{ required: true, validator: checkAge, trigger: "blur" }], //手机号
        stuPassword: [
          //密码
          { required: true, message: "请输入密码", trigger: "blur" },
          { min: 6, max: 16, message: "密码长度至少6位", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
     ...mapActions([
      'gettoken', // 将 `this.gettoken(amount)` 映射为 `this.$store.dispatch('gettoken', amount)` 
    ]),
    // 添加班级信息
    tbadata(e) {
      //获取班级信息接口
        this.axios
          .get("/api/Student/GetClassStudent", {
            params: {
              classId: e
            }
          })
          .then(reject => {
            this.tableData = reject.data;
            this.tabwhether = true;
          });
      
    },
    // 增加、修改学员
    submitForm(formName) {
      let thas = this;
      thas.$refs[formName].validate(valid => {
        if (valid) {
          if (thas.tabbao) {
            //修改学员
            thas.$post("/api/Student/ModifyStudent", {
                stuUid: thas.ruleForm.stuUid, // 要修改学生的唯一标识符
                stuName: thas.ruleForm.stuName, //要修改的名称
                stuBirthDay: thas.ruleForm.stuBirthDay, //要修改的生日
                stuClassId: thas.ruleForm.classId, //班级编号
                stuMobile: thas.ruleForm.stuMobile, //要修改的手机号
                stuPassword: thas.ruleForm.stuPassword, //要修改的密码
                stuSex: thas.ruleForm.stuSex //要修改的性别
              })
              .then(reje => {
                if (reje.data.code === 0) {
                  //数据相同
                  thas.$message(reje.data.message);
                } else if (reje.data.code === 1) {
                  //修改成功
                  thas.$message({
                    message: "修改成功",
                    type: "success"
                  });
                  thas.tabbao=false
                  thas.tbadata(thas.ruleForm.classId); //调用列表数据加载一次
                  // thas.$refs[formName].resetFields(); //清空表单
                  thas.centerDialogVisible = false; //关闭弹框
                } else if (reje.data.code === -1) {
                  //数据异常
                  thas.$message.error(reje.data.message);
                }
              })
              .catch(erro => {
                console.log(erro);
              });
          } else {
            //添加学员
            thas.$post("/api/Student/AddStudent", {
                stuName: thas.ruleForm.stuName, //学生姓名
                stuClassId: thas.ruleForm.classId, //班级编号
                stuBirthDay: thas.ruleForm.stuBirthDay, //生日
                stuMobile: thas.ruleForm.stuMobile, //手机号
                stuPassword: thas.ruleForm.stuPassword, //登录密码,
                stuSex: thas.ruleForm.stuSex //性别
              })
              .then(reject => {
                if (reject.data.code === -3) {
                  thas.$message.error(reject.data.message); //号码相同提示弹框
                } else if (reject.data.code === 1) {
                  thas.$message({
                    //增加成功提示弹框
                    message: "新增成功",
                    type: "success"
                  });
                  thas.$refs[formName].resetFields(); //增加成功清空表单
                  if (
                    thas.tableData.length > 0 ||
                    thas.value === reject.data.data.classId
                  ) {
                    thas.tableData.push(reject.data.data);
                  }
                }
              });
          }
        } else {
          return false;
        }
      });
    },
    //取消表单信息
    resetForm() {
      this.centerDialogVisible = false//取消弹框
    },
    //删除学员信息
    handleDelete(e) {
      let _this = this;
      _this
        .$confirm("删除该学员信息, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
        .then(() => {
          //确认删除
          _this.$get("/api/Student/RemoveStudent", {
              //调用接口删除
              params: {
                uid: e.row.stuUid
              }
            })
            .then(rejct => {
              if (rejct.data.code === 1) {
                //判断接口返回的是1就删除
                _this.tbadata(e.row.classId); //调用加载学员列表
                _this.$message({
                  message: rejct.data.message,
                  type: "success"
                });
              }
            })
            .catch(error => {
              console.log(error);
            });
        })
        .catch(() => {
          _this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    //编辑学员信息
    handleEdit(e) {
      let _this = this;
      _this.centerDialogVisible = true; //弹框出现
      _this.tabbao = true; //改变提交状态
      for (let i in this.ruleForm) {
        this.ruleForm[i] = e.row[i]; //表单赋值
      }
      // this.ruleForm.index = index;
      // console.log(index)
    },
    //新增状态
    centerDiae() {
      for (let i in this.ruleForm) {
        this.ruleForm[i] = "";
      }
      this.ruleForm.stuSex = "男";
      this.centerDialogVisible = true; //弹框状态
      this.tabbao = false; //确认状态
    }
  },

  //过滤器
  filters: {
    formatDate(time) {
      var date = new Date(time);
      return formatDate(date, "yyyy-MM-dd");
    }
  }
};
</script>

<style scoped lang="less">
.text {
  font-size: 14px;
}

.item {
  margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
/deep/.el-table .cell {
  padding-right: 0px;
}
.box-card {
  margin-top: 20px;
}
/deep/.el-input__inner {
  height: 40px;
}
/deep/.el-input__icon {
  line-height: 30px;
}
</style>
